package com.adc.quicktools.process;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import com.adc.quicktools.file.FileControl;


/**
 * 
 * @TypeName: ErrorInputStreamWathThread
 * @Package com.adc.quicktools.process 
 * @Description: TODO( 这个类主要用来处理一个系统调用而新创建一个线程或进程执行期间所产生的出错流的处理 ) 
 * @author shen  shenqiao2012@163.com 
 * @date 2012-6-4 上午02:16:02
 */
public class ErrorInputStreamWathThread extends Thread {
	private Process process = null;
	private boolean over = false;
	private String cmdCharset="UTF-8";
	private String logFile=null;
	private boolean status=false;

	/**
	 * 
	 * @Title: 
	 * @Description: TODO(     输入流处理 )
	 * @param p        子进程
	 * @param cmdCharSet     输入字符集
	 * @param logFile    是否输出日志文件   若输出则给出文件全路径，若不输出，则null
	 */
	public ErrorInputStreamWathThread(Process p,String cmdCharSet,String logFile) {
		process = p;
		this.cmdCharset=cmdCharSet;
		this.logFile=logFile;
		over = false;
	}

	public void run() {
		BufferedReader br=null;
		List<String> linesList =new ArrayList<String>();
		try {
			if (process == null) {
				System.out.println("process为null，无法处理文件转换");
				return;
			}


			//对出错流的处理
			br = new BufferedReader(new InputStreamReader(process.getErrorStream(),cmdCharset));
			
			while (true) {
				if (process == null || over) {
					System.out.println("处理完成");
					break;
				}
				String temp;
				while ((temp = br.readLine()) != null) {
//					logger.info("出错流信息:" + temp);
					System.out.println("出错流信息:" + temp);
					linesList.add(temp);
				}
				if (logFile!=null&&linesList.size()>0) {
					FileControl.writeAsLine(logFile, linesList, true, cmdCharset);
				}
			}
		} catch (Exception e) {
			System.out.println("发生异常" + e.getMessage());
			e.printStackTrace();
		}finally{
			try {
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		status=true;
	}

	public void setOver(boolean over) {
		this.over = over;
	}

	public boolean isStatus() {
		return status;
	}

}
